package logic

import (
	"community/communityrpc/communityrpc"
	"community/communityrpc/internal/svc"
	"community/models/mysqlinit"
	"community/models/redisinit"
	"community/pkg"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *communityrpc.RegisterRequest) (*communityrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var user mysqlinit.User

	mysqlinit.DB.Debug().Where("account = ?", in.Account).Find(&user)

	if user.ID != 0 {
		return nil, fmt.Errorf("账号已被注册，请重新输入")
	}
	result, _ := redisinit.Client.Get("SendSms" + in.Account + "Register").Result()
	if in.SendSms != result {
		return nil, fmt.Errorf("短信验证码错误，请重新输入")
	}
	m := mysqlinit.User{

		Account:  in.Account,
		Password: pkg.Md5pass(in.Password),
	}
	mysqlinit.DB.Debug().Create(&m)

	return &communityrpc.RegisterResponse{
		Id: int64(m.ID),
	}, nil
}
